//
//  ORCodeViewController.swift
//  SwiftWeibo
//
//  Created by Lucky on 16/5/9.
//  Copyright © 2016年 Lucky. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewController: UIViewController {
    
    //底栏
    @IBOutlet weak var customBar: UITabBar!
    
    //波纹top
    @IBOutlet weak var scanLineTop: NSLayoutConstraint!
    
    //外框height
    @IBOutlet weak var containerHeight: NSLayoutConstraint!

    //波纹
    @IBOutlet weak var scanLineView: UIImageView!
    
    @IBOutlet weak var scanResultLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //设置底部视图视图默认选择第0个
        customBar.selectedItem = customBar.items![0]
        customBar.delegate = self
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        //开启动画
        startAnimation()
        
        //开始扫码
        startScan()
    }
    
    private func startAnimation() {
        scanLineTop.constant = -self.containerHeight.constant
        view.layoutIfNeeded()
        
        UIView.animateWithDuration(2.0, animations: {
            self.scanLineTop.constant = self.containerHeight.constant
            UIView.setAnimationRepeatCount(MAXFLOAT)
            self.view.layoutIfNeeded()
        }) { (_) in
            
        }
    }
    
    private func startScan() {
        //1，判断是否能够将输入添加到会话中
        if !session.canAddInput(deviceInput) {
            return
        }
        //2，判断是否能够将输出添加到会话中
        if  !session.canAddOutput(output) {
            return
        }
        //3，将输入和输出添加到会话中
        session.addInput(deviceInput)
        session.addOutput(output)
        //4，设置输出能够解析的数据类型
        output.metadataObjectTypes = output.availableMetadataObjectTypes
        //5，设置输出对象的代理，只要解析成功就会通知代理
        output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
        //6，添加预览图层
        view.layer.insertSublayer(previewLayer, atIndex: 0)
        previewLayer.addSublayer(drawLayer)
        //7，告诉session开始扫描
        session.startRunning()
    }
    
    @IBAction func closeBtnClick(sender: UIBarButtonItem) {
        dismissViewControllerAnimated(true, completion: nil)
    }
        
    // MARK: - 懒加载
    //会话
    private lazy var session: AVCaptureSession = AVCaptureSession()

    //输入设备
    private lazy var deviceInput: AVCaptureDeviceInput? = {
        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        
        do {
            let input = try AVCaptureDeviceInput(device: device)
            return input
        } catch {
            print(error)
            return nil
        }
        
    }()
    
    //输出对象
    private lazy var output: AVCaptureMetadataOutput = AVCaptureMetadataOutput()

    //创建预览图层
    private lazy var previewLayer: AVCaptureVideoPreviewLayer = {
        let layer = AVCaptureVideoPreviewLayer(session: self.session)
        layer.frame = UIScreen.mainScreen().bounds
        return layer
    }()
    
    //创建边线的layer
    private lazy var drawLayer: CALayer = {
        let layer = CALayer()
        layer.frame = UIScreen.mainScreen().bounds
        return layer
    }()

}

extension QRCodeViewController: UITabBarDelegate, AVCaptureMetadataOutputObjectsDelegate {
    func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
        if item.tag == 1 {
            print("二维码")
            
            containerHeight.constant = 300
        
        } else {
            print("条形码")
            
            containerHeight.constant = 150
        }
        
        scanLineView.layer.removeAllAnimations()
        
        startAnimation()
    }
    
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
        
//        print(metadataObjects.last?.stringValue)
        
        scanResultLabel.text = metadataObjects.last?.stringValue
        
        clearCorners()
        
        for object in metadataObjects {
            if object is AVMetadataMachineReadableCodeObject {
                let codeObject = previewLayer.transformedMetadataObjectForMetadataObject(object as! AVMetadataObject) as! AVMetadataMachineReadableCodeObject
                
                drawCorners(codeObject)
            }
        }
        
    }
    
    private func drawCorners(codeObject: AVMetadataMachineReadableCodeObject) {
        
        if codeObject.corners.isEmpty {
            return
        }
        
        // 创建图层
        let layer = CAShapeLayer()
        layer.lineWidth = 4
        layer.strokeColor = UIColor.redColor().CGColor
        layer.fillColor = UIColor.clearColor().CGColor
        // 创建路径
        let path = UIBezierPath()
        var point = CGPointZero
        var index: Int = 0
        
        CGPointMakeWithDictionaryRepresentation((codeObject.corners[index++] as! CFDictionaryRef), &point)
        path.moveToPoint(point)
        
        while index < codeObject.corners.count {
            CGPointMakeWithDictionaryRepresentation((codeObject.corners[index++] as! CFDictionaryRef), &point)
            path.addLineToPoint(point)
        }
        
        path.closePath()
        
        layer.path = path.CGPath
        
        // 将绘制好的图层添加到drawLayer上
        drawLayer.addSublayer(layer)
    }
    
    private func clearCorners() {
        if drawLayer.sublayers == nil || drawLayer.sublayers?.count == 0 {
            return
        }
        
        for subLayer in drawLayer.sublayers! {
            subLayer.removeFromSuperlayer()
        }
    }
}
